﻿using System.Reflection;
using Tpl.Domain.Efxt;

namespace Tpl.Domain
{
    /// <summary>
    /// 获取程序集和实体类，方便在DbContext中
    /// </summary>
    public class EFEntityInfo
    {
        public (Assembly Assembly, IEnumerable<Type> Types) EFEntitiesInfo
            => (GetType().Assembly, GetEntityTypes(GetType().Assembly));

        /// <summary>
        /// 获取所有继承自IEFEntity的实体
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        private IEnumerable<Type> GetEntityTypes(Assembly assembly)
        {
            var efEntities = assembly.GetTypes()
                .Where(m => m.FullName != null
                      && Array.Exists(m.GetInterfaces(), t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEFEntity<>))
                      && !m.IsAbstract
                      && !m.IsInterface)
                .ToArray();

            return efEntities;
        }
    }
}